import React from "react";
import { connect } from "react-redux";
import { Form, message, notification } from "antd";
import { withRouter } from "react-router-dom";
import { login } from "utils/api/userApi";
import { checkIsLogin, setUserData } from "stores/homeStore/action";
import LoginDom from "./loginDom";
import { getStringByTime } from "utils/sayHelloUtils";

const Login = props => {
  const { form, history, checkIsLogin, setUserData } = props;

  const handleSubmit = e => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        const { username, password, remember } = values;
        console.log(remember);
        login(username, password)
          .then(res => {
            const { err, msg, token, data } = res.data;
            if (err === 0) {
              if (localStorage) {
                localStorage.setItem("token", token);
              }
              checkIsLogin(true, true);
              setUserData(data);
              message.success("登录成功！", 1).then(() => {
                const say = getStringByTime();
                const args = {
                  message: `${say.time}，${data.name || username}`,
                  description: say.one,
                  duration: 3
                };
                notification.open(args);
                history.push("/main");
              });
              /*
              如果登录成功则判断是否记住密码
            */
            } else {
              checkIsLogin(false);
              message.error(msg);
            }
          })
          .catch(err => {
            message.error(err.message);
          });
      }
    });
  };
  return <LoginDom handleSubmit={handleSubmit} form={form} />;
};

const LoginWrap = Form.create({ name: "vision_login" })(Login);
export default connect(store => ({}), {
  checkIsLogin,
  setUserData
})(withRouter(LoginWrap));
